from flask import Flask, request, jsonify
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from flask_cors import CORS

app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'super-secret'
CORS(app, resources={r"/*": {"origins": ["http://localhost:8080", "http://127.0.0.1:8080"]}})

jwt = JWTManager(app)

import sqlite3

# 初始化 SQLite 数据库
conn = sqlite3.connect('users.db')
# 创建用户表
conn.execute('''CREATE TABLE IF NOT EXISTS users
             (username TEXT PRIMARY KEY,
              password TEXT NOT NULL,
              permissions TEXT NOT NULL)''')

# 插入初始用户数据
users = [
    ('admin', 'admin123', 'all'),
    ('user', 'user123', 'view')
]
for user in users:
    try:
        conn.execute('INSERT INTO users VALUES (?,?,?)', user)
    except sqlite3.IntegrityError:
        continue
conn.commit()

# 关闭数据库连接
conn.close()

# 封装数据库查询函数
def get_user(username):
    conn = sqlite3.connect('users.db')
    cursor = conn.execute('SELECT * FROM users WHERE username =?', (username,))
    row = cursor.fetchone()
    conn.close()
    if row:
        return {'username': row[0], 'password': row[1], 'permissions': row[2].split(',')}
    else:
        return None

@app.route('/login', methods=['POST'])
def login():
    username = request.json.get('username', None)
    password = request.json.get('password', None)
    user = get_user(username)
    if not user or user['password'] != password:
        return jsonify({'msg': 'Bad username or password'}), 401

    access_token = create_access_token(identity=username)
    return jsonify(access_token=access_token)

@app.route('/permissions', methods=['GET'])
@jwt_required()
def get_permissions():
    current_user = get_jwt_identity()
    user = get_user(current_user)
    if user:
        return jsonify(user['permissions'])
    else:
        return jsonify({'msg': 'User not found'}), 404

@app.route('/dashboard')
def dashboard():
    return {'message': 'This is the dashboard page'}

if __name__ == '__main__':
    app.run(debug=True)